<?php

namespace addons\third\library;

use fast\Http;
use think\facade\Config;
use think\facade\Session;

/**
 * 微信
 */
class WxWechat
{
    const GET_USEROPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 配置信息
     * @var array
     */
    private $config = [];

    public function __construct($options = [])
    {
        if ($config = Config::get('third.wechat')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 获取用户信息
     * @param array $params
     * @return array
     */
    public function getUserInfo($params = [])
    {
        $params = $params ? $params : request()->get();
        if (isset($params['access_token']) || (isset($params['state']) && $params['state'] == Session::get('state') && isset($params['code']))) {
            //获取access_token
            $data = isset($params['code']) ? $this->getOpenid($params['code']) : $params;
            $openid = isset($data['openid']) ? $data['openid'] : '';
            if ($openid) {
                $data = [
                    'access_token'  => '',
                    'refresh_token' => '',
                    'expires_in'    => 300,
                    'openid'        => $openid,
                    'unionid'       => '',
                    'userinfo'      => []
                ];
                return $data;
            }
        }
        return [];
    }

    /**
     * 获取openid
     * @param string code
     * @return array
     */
    public function getOpenid($code = '')
    {
        if (!$code) {
            return [];
        }
        $queryarr = array(
            "appid"      => $this->config['wx_app_id'],
            "secret"     => $this->config['wx_app_secret'],
            "code"       => $code,
            "grant_type" => "authorization_code",
        );
        $response = Http::get(self::GET_USEROPENID_URL, $queryarr);
        $ret = (array)json_decode($response, true);
        return $ret ? $ret : [];
    }
}
